package com.warski.wonderfires.page.firedance;

import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import com.suke.widget.SwitchButton;
import com.warski.wonderfires.R;
import com.warski.wonderfires.TheApplication;
import com.warski.wonderfires.net.JsonStep;
import com.warski.wonderfires.net.TCPConn;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import static com.warski.wonderfires.TheApplication.mContext;

/**
 * tcp协议连接成功页面
 */
public class FireDanceFragment extends Fragment {

    private PopupWindow popupWindow;
    private String tcpClose = "tcpClose";
    private String gearsData = "gearsData";
    private SeekBar gearsBar;
    private String oldData;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_fire_dance, container, false);
        initView(root);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(tcpClose);
        intentFilter.addAction(gearsData);
        mContext.registerReceiver(tcpReceiver, intentFilter);
        return root;
    }
    private BroadcastReceiver tcpReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (tcpClose.equals(action)){
                String data = intent.getStringExtra(tcpClose);
                if (data != null && data.equals(tcpClose) ){
                    NavHostFragment.findNavController(FireDanceFragment.this).navigate(R.id.action_FireDanceFragment_to_DanceFragment);
                }
            }else if (gearsData.equals(action)){
                String data = intent.getStringExtra(gearsData);
                gearsBar.setProgress(Integer.parseInt(data));
                /*if (data != null && !data.equals(oldData)){

                }*/
            }
        }
    };
    private void initView(View root) {

        ImageView titleLeft = root.findViewById(R.id.titleLeft);
        // 设置闹钟视图监听
        titleLeft.setOnClickListener(v -> {
            getPopupWindow();
            popupWindow.showAtLocation(v, Gravity.START,0,0);
        });

        ImageView appName = root.findViewById(R.id.app_name);
        appName.setImageResource(R.mipmap.app_name);

        ImageView fireImage = root.findViewById(R.id.fire_image);
        fireImage.setImageResource(R.mipmap.red_fire);

        ImageView minFireImage = root.findViewById(R.id.min_fire_image);
        minFireImage.setImageResource(R.mipmap.fire);

        ImageView maxFireImage = root.findViewById(R.id.max_fire_image);
        maxFireImage.setImageResource(R.mipmap.fire);

        final SwitchButton titleRight = root.findViewById(R.id.titleRight);
        titleRight.setOnCheckedChangeListener((view, isChecked) -> {
            if (!isChecked){
                new AlertDialog.Builder(root.getContext())
                        .setTitle(R.string.close_device)
                        .setMessage(R.string.close_device_tip)
                        .setPositiveButton(R.string.yes, (dialog, which) -> {
                            TCPConn.getInstance().sendData(JsonStep.FireClose.getJsonString());
                            TCPConn.getInstance().sendData(JsonStep.DeviceClose.getJsonString());
                            new Handler().postDelayed(() -> TCPConn.getInstance().close(),1000);

                        })
                        .setNegativeButton(R.string.no, null)
                        .show();
            }
        });

        gearsBar = root.findViewById(R.id.gears_bar);
        gearsBar.setProgress(0);
        gearsBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) { }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
//                oldData = String.valueOf(progress);
                TCPConn.getInstance().sendData(String.format(JsonStep.FireColorFormatSet.getJsonString(), progress));
                mHandler.postDelayed(mRunnable,300);
            }
        });
    }

    private Handler mHandler = new Handler();
    private Runnable mRunnable = () -> TCPConn.getInstance().sendData(JsonStep.FireLevelSet.getJsonString());

    /***
     * 获取PopupWindow实例
     */
    private void getPopupWindow() {
        if (null != popupWindow) popupWindow.dismiss();
        else initPopupWindow();
    }

    /**
     * 创建PopupWindow
     */
    protected void initPopupWindow() {

        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        // 获取自定义布局文件pop.xml的视图
        View popupWindowView = getLayoutInflater().inflate(R.layout.fire_pop_left_time, null,
                false);
        // 创建PopupWindow实例,200,150分别是宽度和高度
        TextView turnOnTime = popupWindowView.findViewById(R.id.turn_on_time);
        TextView turnOffTime = popupWindowView.findViewById(R.id.turn_off_time);
        popupWindowView.findViewById(R.id.repetition_on_time).setOnClickListener(setTimeClickListener);
        popupWindowView.findViewById(R.id.repetition_off_time).setOnClickListener(setTimeClickListener);
        SwitchButton openSwitchButton = popupWindowView.findViewById(R.id.timing_lights_switch);
        SwitchButton closeSwitchButton = popupWindowView.findViewById(R.id.timed_lights_switch);

        openSwitchButton.setOnCheckedChangeListener((view, isChecked) -> {
            if (isChecked){
                String setTime = turnOnTime.getText().toString();
                String thisTime = df.format(System.currentTimeMillis());
                long nowTime = 0;
                long toTime = 0;
                try {
                    nowTime = df.parse(thisTime).getTime()/1000;
                    toTime = df.parse(setTime + ":00").getTime()/1000;
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                long time;
                if (nowTime < 0) nowTime = 28800 + nowTime;
                if (toTime < 0) toTime = 28800 + toTime;
                if (nowTime > toTime) time = 86400 - nowTime + toTime;
                else time = toTime - nowTime;
                Log.d("timeTime","setTime = " +setTime + ":00" + " thisTime = " + thisTime + " nowTime = " + nowTime + " toTime = " + toTime + " time = " + time);
                TCPConn.getInstance().sendData(String.format(JsonStep.FireScheduleFormatSet.getJsonString(),"open",time));
            }else TCPConn.getInstance().sendData(JsonStep.FireCleanSchedule.getJsonString());
        });
        closeSwitchButton.setOnCheckedChangeListener((view, isChecked) -> {
            if (isChecked){
                String setTime = turnOffTime.getText().toString();
                String thisTime = df.format(System.currentTimeMillis());
                long nowTime = 0;
                long toTime = 0;
                try {
                    nowTime = df.parse(thisTime).getTime()/1000;
                    toTime = df.parse(setTime + ":00").getTime()/1000;
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                long time;
                if (nowTime < 0) nowTime = 28800 + nowTime;
                if (toTime < 0) toTime = 28800 + toTime;
                if (nowTime > toTime) time = 86400 - nowTime + toTime;
                else time = toTime - nowTime;
                Log.d("timeTime","setTime = " +setTime + ":00" + " thisTime = " + thisTime + " nowTime = " + nowTime + " toTime = " + toTime + " time = " + time);
                TCPConn.getInstance().sendData(String.format(JsonStep.FireScheduleFormatSet.getJsonString(),"open",time));
            }else TCPConn.getInstance().sendData(JsonStep.FireCleanSchedule.getJsonString());
        });

        turnOnTime.setOnClickListener(setTimeClickListener);
        turnOffTime.setOnClickListener(setTimeClickListener);
        popupWindow = new PopupWindow(popupWindowView, TheApplication.width*2/3, TheApplication.height, true);
        // 设置动画效果
        popupWindow.setAnimationStyle(R.style.AnimationFade);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);

    }
    private View.OnClickListener setTimeClickListener = v -> {
        TextView textView = (TextView) v;
        String[] strings = textView.getText().toString().split(":");
        int oldHour = Integer.parseInt(strings[0]);
        int oldMinute = Integer.parseInt(strings[1].startsWith("0")? strings[1].substring(strings[1].length() - 1) : strings[1]);
        new TimePickerDialog(getContext(), AlertDialog.THEME_HOLO_LIGHT, (view, hourOfDay, minute) -> {
            if (minute < 10) textView.setText(String.format("%d:0%d", hourOfDay, minute));
            else textView.setText(String.format("%d:%d", hourOfDay, minute));
        }, oldHour, oldMinute, true).show();
    };

    @Override
    public void onDestroy() {
        if (popupWindow != null){
            popupWindow.dismiss();
            popupWindow = null;
        }
        if (mHandler != null){
            mHandler.removeCallbacks(mRunnable);
            mRunnable = null;
            mHandler = null;
        }
        mContext.unregisterReceiver(tcpReceiver);
        super.onDestroy();
    }
}
